08. Exercise: Add a Content Intent
L1 A08 Add A Content Intent
Android Developer Documentation
Exercise
- Open
NotificationUtils.ktand find thesendNotification()extension function. First, you need to create an intent with yourapplicationContextand the activity to be launched.
// NotificationUtils.kt
fun NotificationManager.sendNotification(messageBody: String, applicationContext: Context) {
// Create the content intent for the notification, which launches
// this activity
// TODO: Step 1.11 create intent
val contentIntent = Intent(applicationContext, MainActivity::class.java)
Next, you need to create a new PendingIntent . The system will use the pending intent to open your app.
- Create a
PendingIntentwithapplicationContext, notification id, the content intent you created in the previous step and thePendingIntentflag. ThePendingIntentflag specifies the option to create a newPendingIntentor use an existing one. You need to setPendingIntent.FLAG_UPDATE_CURRENTas the flag since you don’t want to create a new notification but to update if there is an existing one. This way you will be modifying the currentPendingIntentwhich is associated with the Intent you are supplying.
// NotificationUtils.kt
// TODO: Step 1.12 create PendingIntent
val contentPendingIntent = PendingIntent.getActivity(
applicationContext,
NOTIFICATION_ID,
contentIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
- Next, pass the
PendingIntentto your notification. You do this by callingsetContentIntent()on theNotificationBuilder. Now when you click the notification, thePendingIntentwill be triggered, opening up yourMainActivity.
- Also set
setAutoCancel()totrue, so that when the user taps on the notification, the notification dismisses itself as it takes you to the app.
// NotificationUtils.kt
// Build the notification
val builder = NotificationCompat.Builder(applicationContext,
applicationContext.getString(R.string.default_notification_channel_id)
)
.setSmallIcon(R.drawable.cooked_egg)
.setContentTitle(applicationContext.getString(R.string.notification_title))
.setContentText(messageBody)
// TODO: Step 1.13 set content intent
.setContentIntent(contentPendingIntent)
.setAutoCancel(true)
- Now run the app again, set a timer, put the app in the background and wait for the notification to appear. Once you see the notification, click on the notification by pulling the status bar and observe how the app is brought to the foreground.